﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;


using Newtonsoft.Json;
using System.Configuration;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.Dynamic;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using Microsoft.JScript;

using Trade.DBUtility;
using Trade.DBUtility.DataTableName;


namespace TradeWeb.Controllers
{
    public class TaskController : Controller
    {
        #region 查询工作任务列表
        public string GetTaskList(string strUserCode)
        {
            string jsonResult = string.Empty;
            DataSet dsResult = null;

            DataSet dsTemp = null;
            #region 获取工作任务数据集
            DataTableName dtnTable = new DataTableName();
            dtnTable.strSelectSQL = "SELECT * FROM T_Task WHERE ISDel=0 AND ISNo=1 AND Creater= @Creater ";
            dtnTable.strTableName = "T_Task";
            dtnTable.SqlSelectParameterList.Add(new SqlParameter("@Creater", strUserCode));
            try
            {
                dsTemp = CustomizableDesignBLL.GetData(dtnTable, false);
            }
            catch (Exception)
            {
                jsonResult = "{\"success\":false,\"data\":{},\"message\":\"数据查询失败！\"}";
                return jsonResult;
            }
            if (dsTemp == null || dsTemp.Tables.Count <= 0 || dsTemp.Tables[0].DefaultView.Count <= 0)
            {
                jsonResult = "{\"success\":false,\"data\":{},\"message\":\"系统未查询到相关数据！\"}";
                return jsonResult;
            }
            #endregion

            try
            {
                DataTable T_7Day = dsTemp.Tables["T_Task"].Clone();
                T_7Day.TableName = "T_7Day";
                DataTable T_7Later = dsTemp.Tables["T_Task"].Clone();
                T_7Later.TableName = "T_7Later";
                DataTable T_Over = dsTemp.Tables["T_Task"].Clone();
                T_Over.TableName = "T_Over";
                #region 克隆表结构，分组数据集到3个数据表中。
                foreach (DataRow drRow in dsTemp.Tables["T_Task"].Rows)
                {
                    DateTime dtimeCompleteDate = DateTime.Parse(drRow["CompleteDate"].ToString());
                    DateTime dtime7Day = DateTime.Now.AddDays(7);

                    if (dtimeCompleteDate.CompareTo(DateTime.Now) < 0)   //超期
                    {
                        T_Over.Rows.Add(drRow.ItemArray);
                    }
                    else if (dtimeCompleteDate.CompareTo(dtime7Day) > 0)   //7天后  
                    {
                        T_7Later.Rows.Add(drRow.ItemArray);
                    }
                    else  //7天内
                    {
                        T_7Day.Rows.Add(drRow.ItemArray);
                    }
                }
                #endregion

                dsResult = new DataSet();
                dsResult.Tables.Add(T_7Day);
                dsResult.Tables.Add(T_7Later);
                dsResult.Tables.Add(T_Over);

                jsonResult = "{\"success\":true  ,\"data\":" + JsonConvert.SerializeObject(dsResult) + "  ,\"message\":\"正常\"}";
                return jsonResult;
            }
            catch (Exception)
            {
                jsonResult = "{\"success\":false ,\"data\":{},\"message\":\"分解数据集到不同的分组中失败！\"}";
                return jsonResult;
            }
        }
        #endregion

        #region 查询工作任务详情
        public string GetTaskDetail(string strSerialNum) 
        {
            string jsonResult = string.Empty;
            DataSet dsResult = null;
            #region 获取公告详情
            DataTableName dtnTable = new DataTableName();
            dtnTable.strSelectSQL = "SELECT  SerialNum ,ISDel ,CONVERT(VARCHAR(10), Dates, 20) AS Dates ,UserCode ,CNUserName ,ENUserName ,DeptCode ,CNDeptName ,ENDeptname ,Title ,Task ,CONVERT(VARCHAR(10), CompleteDate, 20) AS CompleteDate ,ISCancel ,ISYes , CASE WHEN ISNULL(ISYes, 0)= 0 AND ISNULL(ISNo,0) = 0 AND ISNULL(ISCancel,0)= 0 THEN '无状态信息' WHEN ISNULL(ISYes, 0)= 1 AND ISNULL(ISNo,0) = 0 AND ISNULL(ISCancel,0)= 0 THEN '已结束' WHEN ISNULL(ISYes, 0)= 0 AND ISNULL(ISNo,0) = 1 AND ISNULL(ISCancel,0)= 0 THEN '未结束' WHEN ISNULL(ISYes, 0)= 0 AND ISNULL(ISNo,0) = 0 AND ISNULL(ISCancel,0)= 1 THEN '取消' END AS CompleteState,ISNo ,Creater ,CreaterName FROM dbo.T_Task where isDel=0 and SerialNum=@SerialNum";
            dtnTable.strTableName = "T_Task";
            dtnTable.SqlSelectParameterList.Add(new SqlParameter("@SerialNum", strSerialNum));
            try
            {
                dsResult = CustomizableDesignBLL.GetData(dtnTable, false);
            }
            catch (Exception)
            {
                jsonResult = "{\"success\":false,\"data\":{},\"message\":\"数据查询失败！\"}";
                return jsonResult;
            }
            if (dsResult == null || dsResult.Tables.Count <= 0 || dsResult.Tables[0].DefaultView.Count <= 0)
            {
                jsonResult = "{\"success\":false,\"data\":{},\"message\":\"系统未查询到相关数据！\"}";
                return jsonResult;
            }
            #endregion
            try
            {
                for (int i = 0; i < dsResult.Tables["T_Task"].Rows.Count; i++)
                {
                    string strBody = dsResult.Tables["T_Task"].Rows[i]["Task"].ToString();
                    //每一个换行符，都重新生成一个段落。
                    string[] aryPhrase = strBody.Split(new char[] { '\r', '\n' });
                    string strNewBody = string.Empty;
                    strNewBody = strBody.Replace("\r\n", "<br>").Replace("\r", "<br>").Replace("\n", "<br>");
                    strNewBody = strNewBody.Replace("\0", "&nbsp;&nbsp;").Replace(" ", "&nbsp;&nbsp;");
                    dsResult.Tables["T_Task"].DefaultView[i]["Task"] = strNewBody;
                    dsResult.Tables["T_Task"].DefaultView[i].EndEdit();
                }
                jsonResult = "{\"success\":true  ,\"data\":" + JsonConvert.SerializeObject(dsResult) + ",\"message\":\"正常\"}";
                return jsonResult;
            }
            catch (Exception)
            {
                jsonResult = "{\"success\":false,\"data\":{},\"message\":\"格式化公告详情内容失败！\"}";
                return jsonResult;
            }
        }
        #endregion

        #region 修改工作任务状态
        public string SetTaskState(string strSerialNum, string strStateFlag)
        {
            string jsonResult = string.Empty;

            //验证是否提供必须的参数
            if (string.IsNullOrEmpty(strSerialNum))
            {
                jsonResult = "{\"success\":false,\"data\":{},\"message\":\"未提供工作任务单号！\"}";
            }
            if(string.IsNullOrEmpty(strStateFlag))
            {
                jsonResult = "{\"success\":false,\"data\":{},\"message\":\"未提供接口参数！\"}";
            }

            //验证接口的协议参数是否符合协议约定
            int iFlag = -1;
            iFlag = System.Convert.ToInt32(strStateFlag);
            bool bMatch = iFlag == 10 || iFlag == 20 || iFlag == 30;
            if (!bMatch)
            {
                jsonResult = "{\"success\":false,\"data\":{},\"message\":\"接口参数不正确！\"}";
            }
            //iFlag=10 未结束 
            //iFlag=20 已结束
            //iFlag=30 取消
            #region 定义状态改变接口协议参数
            int iYesStatus = -1;
            int iNoStatus = -1;
            int iCancelStatus = -1;
            if (iFlag == 10)
            {
                iYesStatus = 0;
                iNoStatus = 1;
                iCancelStatus = 0;
            }
            else if (iFlag == 20)
            {
                iYesStatus = 1;
                iNoStatus = 0;
                iCancelStatus = 0;
            }
            else if (iFlag == 30)
            {
                iYesStatus = 0;
                iNoStatus = 0;
                iCancelStatus = 1;
            }
            #endregion
            try
            {
                DataTableName dtnTable = new DataTableName();
                dtnTable.strExecSQL = "UPDATE T_Task SET ISYes=@ISYes,ISNo=@ISNo,ISCancel=@ISCancel WHERE SerialNum=@SerialNum AND ISDel=0";
                dtnTable.SqlExecParameterList.Add(new SqlParameter("@SerialNum", strSerialNum));
                dtnTable.SqlExecParameterList.Add(new SqlParameter("@ISYes", iYesStatus));
                dtnTable.SqlExecParameterList.Add(new SqlParameter("@ISNo", iNoStatus));
                dtnTable.SqlExecParameterList.Add(new SqlParameter("@ISCancel", iCancelStatus));
                CustomizableDesignBLL.ExecSQL(dtnTable);
                jsonResult = "{\"success\":true ,\"data\":{},\"message\":\"更新成功！\"}";
                return jsonResult;
            }
            catch (Exception)
            {
                jsonResult = "{\"success\":false,\"data\":{},\"message\":\"更新失败！\"}";
                return jsonResult;
            }
        }
        #endregion

        #region 反射：利用反射，求出控制器中，接口方法的完整网络地址（包含地址栏参数）
        public string Method()
        {
            TaskController au = new TaskController();
            Type t = typeof(TaskController);
            string strControler = "TaskController";
            strControler = strControler.Replace("Controller", "").Trim();

            string jsonResult = "";
            List<string> lstResult = new List<string>();
            List<string> lstMethod = new List<string>();
            System.Collections.Hashtable hsParams = new System.Collections.Hashtable();


            System.Reflection.MethodInfo[] methods = t.GetMethods();
            for (int i = 0; i < methods.Length; i++)
            {
                System.Reflection.MethodInfo me = methods[i];
                string meName = me.Name;
                lstMethod.Add(meName);

                System.Reflection.ParameterInfo[] pars = me.GetParameters();
                for (int j = 0; j < pars.Length; j++)
                {
                    System.Reflection.ParameterInfo pa = pars[j];
                    string paName = pa.Name;
                    hsParams.Add(meName + j, paName);
                }
            }
            string strAddress1 = "localhost:5350/" + strControler + "/";
            for (int i = 0; i < lstMethod.Count; i++)
            {
                string strParas = "";
                string strMeName = lstMethod[i];
                foreach (System.Collections.DictionaryEntry item in hsParams)
                {
                    //KEY名称的长度仅比对应的方法的名称的长度多一位；（进行一次过滤；）
                    int iMeLength = strMeName.Length;
                    int iKeyLength = item.Key.ToString().Length;
                    bool bIsSure = iKeyLength - iMeLength == 1;

                    if (item.Key.ToString().Trim().Contains(strMeName.Trim()) && bIsSure)
                    {
                        strParas += item.Value.ToString() + "=&";
                    }
                }
                string strAddress = strAddress1 + strMeName + "?" + strParas;
                if (strAddress.EndsWith("&"))
                {
                    strAddress = strAddress.Substring(0, strAddress.Length - 1);
                }
                //正常情况下，我们创建的方法，会排序在类，在FrameWork中默认生成的方法的前面。（所以取最后一个自定义的方法名可以再次过滤；）
                if (strAddress.Contains("Method"))
                    break;
                lstResult.Add(strAddress);
            }
            jsonResult = JsonConvert.SerializeObject(lstResult);
            return jsonResult;
        }
        #endregion
    }
}
